package com.data2wisdom.comm.extend.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

import javax.persistence.Id;

import org.apache.log4j.Logger;
import org.springframework.core.convert.support.ConversionServiceFactory;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.convert.support.GenericConversionService;

import com.data2wisdom.comm.extend.model.Param;

public class HandleAttributeUtil {	
	private static Logger logger = Logger.getLogger(HandleAttributeUtil.class);
	
	public static Object findAttribute(int nr, String code,List<Param> params) {
		if (params == null || params.size() <= 0){
			return null;
		}
		for (Param param : params) {
			if (param.getRn() == nr && param.getName().equals(code)){
				//区分是否是大字段
				if(param.getIsBigData() == 0){
					return param.getValue();
				}
				else if(param.getIsBigData() == 1){
					return param.getBigData();
				}
				else if(param.getIsBigData() == 2){
					return param.getClobData();
				}
			}
		}
		return null;
	}
	
	public static Object getAttributeObject(String code,List<Param> params) {
		return findAttribute(0, code,params);
	}
	/**
	 * 从数据库获取数据，填充bean对象的通过Java注解标出要保存的变量,bean原有其他变量值不能丢。
	 * @param params
	 * @param dataBean
	 * @return
	 */
	public static <T>  T convertParamsToBean(List<Param> params,T dataBean)
	{
		if(params == null)
			return null;
		
		BeanInfo beanInfo = null;
		try {
			beanInfo = Introspector.getBeanInfo(dataBean.getClass());
		} catch (Exception e) {
			logger.error("获取bean信息异常", e);
			return null;
		}
		
		PropertyDescriptor[] attributes = beanInfo.getPropertyDescriptors();
		for(PropertyDescriptor property:attributes)
		{
			if(property.getName().equals("class"))
				continue;
			Class type = property.getPropertyType();
			try {
				String name = property.getName();
				Method writeMethod = property.getWriteMethod();
				if(writeMethod == null)
					continue;
				
				Object value =  HandleAttributeUtil.getAttributeObject(name, params);
				//value = ValueObjectUtil.typeCast(value, type);
				
				writeMethod.invoke(dataBean, value);
				
			} catch (Exception e) {
				logger.error("封装对象异常：bean class["+ dataBean.getClass().getName() +"],param info["+ params.toString()+ "]",e );
				continue;
			} 
		}
		
		return dataBean;
		
	}
	
	public static <T>  T convertBean(List<Param> params,T dataBean){
		if(params == null || params.size() == 0)
			return null;
		
		Field [] fields = dataBean.getClass().getDeclaredFields();
		Field [] superFields = dataBean.getClass().getSuperclass().getDeclaredFields();
		
		for(Field field :superFields){
			field.setAccessible(true);
			 if(field.isAnnotationPresent(Id.class)){
					field.setAccessible(true);
					Class<?> type = field.getType();
					String name = field.getName();
					Object value = params.get(0).getNodeId();
					if(value != null){
						DefaultConversionService conversionService = new DefaultConversionService();
						conversionService.addConverter(new StringToDateConverter());
						Object targetTypeValue = conversionService.convert(value,type);
						try {
							field.set(dataBean, targetTypeValue);
						} catch (Exception e) {
							logger.error("属性"+name+"赋值异常", e);
						} 
					}
			 }
		 }
		for(Field field : fields){
			field.setAccessible(true);
			Class<?> type = field.getType();
			String name = field.getName();
			Object value =  HandleAttributeUtil.getAttributeObject(name, params);
			if(value != null){
				DefaultConversionService conversionService = new DefaultConversionService();
				conversionService.addConverter(new StringToDateConverter());
				Object targetTypeValue = conversionService.convert(value,type);
				try {
					field.set(dataBean, targetTypeValue);
				} catch (Exception e) {
					logger.error("属性"+name+"赋值异常", e);
					continue;
				} 
			}
		}
		
		return dataBean;
	}
	
}
